<template>
	<view class="order-list">
		<!-- 状态分类 -->
		<view class="tabs">
			<view 
				class="tab-item" 
				v-for="(item, index) in tabs" 
				:key="index"
				:class="{active: currentTab === index || (currentTab === null && index === 0)}"
				@tap="switchTab(index)"
			>
				<text>{{item}}</text>
			</view>
		</view>

		<!-- 订单列表 -->
		<scroll-view 
			class="order-scroll" 
			scroll-y 
			@scrolltolower="loadMore"
			v-if="orderList && orderList.length > 0"
			:style="{ height: scrollHeight + 'px' }"
		>
			<view class="order-item" v-for="(item, index) in orderList" :key="index">
				<!-- 订单状态 -->
				<view class="header">
					<text class="time">{{item.create_time | formatDate}}</text>
					<text class="status" :class="'status-' + item.status">{{statusMap[item.status]}}</text>
				</view>

				<!-- 商品信息 -->
				<view class="goods" @tap="navTo('/pages/order/detail?id=' + item._id)">
					<view class="goods-item" v-for="(good, idx) in item.goods_list" :key="idx">
						<image :src="good.cover" mode="aspectFill"></image>
						<view class="info">
							<view class="name text-ellipsis">{{good.name}}</view>
							<view class="spec">{{good.spec_name}}</view>
							<view class="price-box">
								<text class="price">¥{{good.price}}</text>
								<text class="num">x{{good.num}}</text>
							</view>
						</view>
					</view>
				</view>

				<!-- 订单金额 -->
				<view class="footer">
					<view class="total">
						<text>共{{item.goods_list.length}}件商品 实付款:</text>
						<text class="price">¥{{item.total_price}}</text>
					</view>
					<!-- 订单操作按钮 -->
					<view class="action">
						<view class="btn" v-if="item.status === 0" @tap="payOrder(item)">立即支付</view>
						<view class="btn" v-if="item.status === 2" @tap="confirmOrder(item)">确认收货</view>
						<view class="btn plain" v-if="item.status === 3" @tap="deleteOrder(item)">删除订单</view>
					</view>
				</view>
			</view>
		</scroll-view>

		<!-- 空状态 -->
		<view class="empty" v-else>
			<view class="empty-icon">
				<u-icon name="order" size="80" color="#999"></u-icon>
			</view>
			<view class="empty-text">
				<view class="title">暂无相关订单</view>
				<view class="desc">快去选购商品吧</view>
			</view>
			<view class="empty-btn" @tap="goShopping">
				<text>去逛逛</text>
				<u-icon name="arrow-right" size="24" color="#018d71"></u-icon>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				tabs: ['全部', '待付款', '待发货', '待收货', '已完成'],
				currentTab: 0,
				orderList: [],
				page: 1,
				loading: false,
				scrollHeight: 0,
				statusMap: {
					0: '待付款',
					1: '待发货',
					2: '待收货',
					3: '已完成',
					4: '退款中',
					5: '已退款',
					6: '退款驳回'
				}
			}
		},
		filters: {
			formatDate(timestamp) {
				if(!timestamp) return ''
				const date = new Date(timestamp)
				return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
			}
		},
		onLoad(e) {
			// 设置默认选中标签
			if(e.type !== undefined) {
				this.currentTab = Number(e.type) + 1
			}
			// 计算scroll-view高度
			this.calcScrollHeight()
			this.getOrderList()
		},
		onPullDownRefresh() {
			// 重置页码
			this.page = 1
			// 清空列表
			this.orderList = []
			// 重新加载数据
			this.getOrderList()
		},
		// 监听窗口尺寸变化
		onResize() {
			this.calcScrollHeight()
		},
		methods: {
			// 计算scroll-view高度
			calcScrollHeight() {
				const systemInfo = uni.getSystemInfoSync()
				// 减去tabs高度(120rpx)和页面上下padding(30rpx)
				this.scrollHeight = systemInfo.windowHeight - uni.upx2px(120) - uni.upx2px(30)
			},
			// 切换标签
			switchTab(index) {
				if(this.currentTab === index || (this.currentTab === null && index === 0)) return
				this.currentTab = index
				this.page = 1
				this.orderList = []
				this.getOrderList()
			},
			// 获取订单列表
			getOrderList() {
				vk.callFunction({
					url: 'client/order/kh/list',
					data: {
						where: this.getQueryCondition(),
						page: this.page,
						pageSize: 10
					},
					success: (data) => {
						if(data && data.rows) {
							this.orderList = this.page === 1 ? data.rows : [...this.orderList, ...data.rows]
						} else {
							this.orderList = []
						}
						// 停止下拉刷新动画
						uni.stopPullDownRefresh()
					},
					fail: (err) => {
						console.error('获取订单列表失败:', err)
						this.orderList = []
						uni.showToast({
							title: '获取订单列表失败',
							icon: 'none'
						})
						// 停止下拉刷新动画
						uni.stopPullDownRefresh()
					}
				})
			},
			// 获取查询条件
			getQueryCondition() {
				let uid = vk.getVuex('$user.userInfo._id')
			
				// 待付款：status=0 且 pay_status=0
				if(this.currentTab === 1) {
					return {
						uid,
						status: 0,
						pay_status: 0
					}
				}
				// 待发货：status=1 或 (status=0 且 pay_status=1)
				if(this.currentTab === 2) {
					return {
						uid,
						status: 1
					}
				}
				// 待收货
				if(this.currentTab === 3) {
					return {
						uid,
						status: 2
					}
				}
				// 已完成
				if(this.currentTab === 4) {
					return {
						uid,
						status: 3
					}
				}
				return {
						uid
					}
			},
			// 加载更多
			loadMore() {
				if(this.loading) return
				this.loading = true
				this.page++
				vk.callFunction({
					url: 'client/order/kh/list',
					data: {
						where: this.getQueryCondition(),
						page: this.page,
						pageSize: 10
					},
					success: (data) => {
						if(data && data.rows && data.rows.length) {
							this.orderList = [...this.orderList, ...data.rows]
						} else {
							this.page--
							uni.showToast({
								title: '没有更多订单了',
								icon: 'none'
							})
						}
					},
					complete: () => {
						this.loading = false
					}
				})
			},
			// 支付订单
			payOrder(order) {
				uni.navigateTo({
					url: `/pages/order/detail?id=${order._id}`
				})
			},
			// 确认收货
			confirmOrder(order) {
				uni.showModal({
					title: '提示',
					content: '确认已收到商品？',
					success: res => {
						if(res.confirm) {
							vk.callFunction({
								url: 'client/order/kh/confirm',
								data: {
									id: order._id
								},
								success: () => {
									uni.showToast({
										title: '确认成功'
									})
									this.getOrderList()
								}
							})
						}
					}
				})
			},
			// 删除订单
			deleteOrder(order) {
				uni.showModal({
					title: '提示',
					content: '确定要删除该订单吗？',
					success: res => {
						if(res.confirm) {
							vk.callFunction({
								url: 'client/order/kh/remove',
								data: {
									id: order._id
								},
								success: () => {
									uni.showToast({
										title: '删除成功'
									})
									this.getOrderList()
								}
							})
						}
					}
				})
			},
			// 页面跳转
			navTo(url) {
				uni.navigateTo({
					url
				})
			},
			// 跳转到商品列表
			goShopping() {
				uni.switchTab({
					url: '/pages/goods/list'
				})
			}
		},
	}
</script>

<style lang="scss" scoped>
.order-list {
	min-height: 100vh;
	background-color: #f8f8f8;
	padding: 0 0 30rpx;

	.tabs {
		display: flex;
		background-color: #fff;
		padding: 20rpx 0;
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 10;
		box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);

		.tab-item {
			flex: 1;
			text-align: center;
			position: relative;
			padding: 16rpx 0;
			font-size: 30rpx;
			color: #999;
			transition: all 0.3s;

			&.active {
				color: #018d71;
				font-weight: bold;
				
				&::after {
					content: '';
					position: absolute;
					left: 50%;
					bottom: -4rpx;
					transform: translateX(-50%);
					width: 40rpx;
					height: 4rpx;
					background-color: #018d71;
					border-radius: 2rpx;
				}
			}
			
			&:active {
				opacity: 0.8;
			}
		}
	}

	.order-scroll {
		padding: 120rpx 20rpx 0;
		box-sizing: border-box;
		width: 100%;

		.order-item {
			background-color: #fff;
			border-radius: 16rpx;
			margin-bottom: 20rpx;
			box-shadow: 0 2rpx 12rpx rgba(0,0,0,0.03);
			overflow: hidden;

			.header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 24rpx 30rpx;
				border-bottom: 1rpx solid #f5f5f5;

				.time {
					font-size: 26rpx;
					color: #999;
				}

				.status {
					font-size: 28rpx;
					font-weight: 500;
					
					&.status-0 {
						color: #ff6b6b;
					}
					&.status-1 {
						color: #02a584;
					}
					&.status-2 {
						color: #018d71;
					}
					&.status-3 {
						color: #999;
					}
				}
			}

			.goods {
				padding: 20rpx;

				.goods-item {
					display: flex;
					padding: 16rpx 0;

					image {
						width: 120rpx;
						height: 120rpx;
						border-radius: 12rpx;
						margin-right: 20rpx;
						box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
					}

					.info {
						flex: 1;
						width: 0;

						.name {
							font-size: 28rpx;
							color: #333;
							margin-bottom: 12rpx;
							line-height: 1.4;
							@extend .text-ellipsis;
						}

						.spec {
							font-size: 24rpx;
							color: #999;
							margin-bottom: 16rpx;
							background-color: #f8f8f8;
							padding: 4rpx 12rpx;
							border-radius: 4rpx;
							display: inline-block;
						}

						.price-box {
							display: flex;
							justify-content: space-between;
							align-items: center;

							.price {
								font-size: 32rpx;
								color: #f00;
								font-weight: bold;
							}

							.num {
								font-size: 26rpx;
								color: #999;
							}
						}
					}
				}
			}

			.footer {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 20rpx;
				border-top: 1rpx solid #f5f5f5;
				background-color: #fafafa;

				.total {
					font-size: 26rpx;
					color: #666;
					flex-shrink: 0;

					.price {
						color: #f00;
						font-size: 32rpx;
						font-weight: bold;
						margin-left: 8rpx;
					}
				}

				.action {
					display: flex;
					align-items: center;

					.btn {
						min-width: 160rpx;
						height: 64rpx;
						line-height: 64rpx;
						text-align: center;
						background: linear-gradient(135deg, #02a584 0%, #018d71 100%);
						color: #fff;
						border-radius: 32rpx;
						font-size: 26rpx;
						box-shadow: 0 4rpx 12rpx rgba(1,141,113,0.2);
						margin-left: 20rpx;
						transition: transform 0.2s;
						
						&:active {
							transform: translateY(2rpx);
						}
						
						&.plain {
							background: #fff;
							color: #666;
							border: 1rpx solid #ddd;
							box-shadow: none;
						}
					}
				}
			}
		}
	}

	.empty {
		padding-top: 200rpx;
		text-align: center;
		
		.empty-icon {
			margin-bottom: 40rpx;
			
			/* 添加图标动画效果 */
			animation: float 3s ease-in-out infinite;
		}
		
		.empty-text {
			.title {
				font-size: 32rpx;
				color: #333;
				font-weight: 500;
				margin-bottom: 16rpx;
			}
			
			.desc {
				font-size: 26rpx;
				color: #999;
			}
		}
		
		.empty-btn {
			margin-top: 60rpx;
			display: inline-flex;
			align-items: center;
			padding: 20rpx 40rpx;
			background-color: rgba(1,141,113,0.1);
			border-radius: 40rpx;
			
			text {
				font-size: 28rpx;
				color: #018d71;
				margin-right: 8rpx;
			}
			
			&:active {
				transform: scale(0.98);
			}
		}
	}

	/* 图标浮动动画 */
	@keyframes float {
		0% {
			transform: translateY(0);
		}
		50% {
			transform: translateY(-20rpx);
		}
		100% {
			transform: translateY(0);
		}
	}
}

.text-ellipsis {
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}
</style>
